﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Workflow.DwzCode;

namespace H2.NET.Web.Pages.SMD.InStock
{
    public partial class StockMaintain : BasePage
    {
        public string BalanceBudget = string.Empty;
        private readonly ConfigService _configService = new ConfigService();

        private string Area
        {
            get
            {
                var area = AksRequest.GetString("area");
                if (string.IsNullOrEmpty(area))
                {
                    area = "上海";
                }
                return area;
            }
        }

        private string Code
        {
            get
            {
                switch (Area)
                {
                    case "上海" :
                        return "SHXYYS";
                    case "广州":
                        return "GZXYYS";
                    case "廊坊":
                        return "LFXYYS";
                    default:
                        return "";
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            var dic = new Dictionary<string, string>
            {
                {"S_TSJLX", "调色机"},
                {"S_ZDJLX", "震荡机"},
                {"S_DNXH", "电脑"}
            };

            if (AksRequest.GetString("action") == "save")
            {
                // 获取所有型号的配置
                var dt = _configService.GetList("name <> '不需要' and ParentId in (select configid from t_smd_Config where code in ('S_TSJLX','S_ZDJLX','S_DNXH')) order by seq").Tables[0];
                // 获取父级配置
                var parentDt = _configService.GetList(" code in ('S_TSJLX','S_ZDJLX','S_DNXH')").Tables[0];
                // 获取所有库存
                var inStocks = (t_smd_InStock._Area == Area).List<t_smd_InStock>(Storage.Context3);

                var list = new List<t_smd_InStock>();
                decimal total_amount = 0;
                var kc_content = "";
                foreach (DataRow row in dt.Rows)
                {
                    var code = row["code"].ToString();
                    var id = AksRequest.GetString("id_" + code);
                    var price = AksRequest.GetString("Price_" + code);
                    var initQuantity = AksRequest.GetInt("Number_" + code, 0);
                    var amount = AksRequest.GetString("Amount_" + code).Replace(",", "");
                    var remark = AksRequest.GetString("Remark_" + code);
                    total_amount += Utils.StrToDecimal(amount, 0);

                    var inStock = new t_smd_InStock();
                    inStock.Area = Area;
                    if (Utils.StrToInt(id, 0) > 0)
                    {
                        inStock = inStocks.FirstOrDefault(t => t.ID == Utils.StrToInt(id, 0));
                        inStock.InitQuantity += initQuantity;

                    }
                    else
                    {
                        inStock.GroupName = parentDt.Select("configid=" + row["parentid"])[0]["name"].ToString();
                        inStock.Name = row["name"].ToString();
                        inStock.Code = code;
                        inStock.InitQuantity = initQuantity;
                        inStock.SendQuantity = 0;
                    }
                    inStock.Price = Utils.StrToDecimal(price.Replace(",", ""), 0);
                    inStock.Remark = remark;

                    // 读取原有的数据
                    if (Utils.StrToInt(id, 0) == 0)
                    {
                        inStock.EntityState._Loaded = false;
                    }
                    list.Add(inStock);

                    if (initQuantity > 0) kc_content += code + ":增加了" + initQuantity + "," + remark + ";\n";
                }
                Storage.Save(Storage.Context3, list.ToArray());

                if (!string.IsNullOrEmpty(kc_content))
                {
                    var inStockLog = new t_smd_InStockLog();
                    inStockLog.Category = "库存变更";
                    inStockLog.Amount = total_amount*-1;
                    inStockLog.Content = Area + "\n" + kc_content;
                    inStockLog.CreateOn = DateTime.Now;
                    inStockLog.CreaterName = UserAPI.UserFullName;
                    Storage.Save(Storage.Context3, inStockLog);

                    // 扣除预算
                    var sql = "update t_smd_Config set value = cast(value as decimal) + "
                              + inStockLog.Amount
                              + "where code = '"
                              + Code
                              + "' and ParentId = (select configid from t_smd_Config where code='S_XYYS')";
                    _configService.BatchUpdate(sql);
                }
                // 记录日志
                if (total_amount > 0)
                {
                    var inStockLog = new t_smd_InStockLog();
                    inStockLog.Category = "设备预算";
                    inStockLog.Amount = total_amount*-1;
                    inStockLog.Content = Area + "-使用了预算:" + total_amount.ToString("N") + ";";
                    inStockLog.CreateOn = DateTime.Now;
                    inStockLog.CreaterName = UserAPI.UserFullName;
                    Storage.Save(Storage.Context3, inStockLog);
                }

                SuccessMsg("BI/InStock/Index.aspx");
            }
            else
            {
                var str_where = "ParentId = (select configid from t_smd_Config where code='S_XYYS') ";

                var dt = _configService.GetList(str_where + " and code = '" + Code + "'").Tables[0];
                BalanceBudget = Utils.StrToDecimal(dt.Rows[0]["value"].ToString(), 0).ToString("N");
                rpt_model.DataSource = dic;
                rpt_model.DataBind();
            }
        }

        protected void rpt_model_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.AlternatingItem && e.Item.ItemType != ListItemType.Item) return;

            var hCode = e.Item.FindControl("h_code") as System.Web.UI.HtmlControls.HtmlInputHidden;
            var rptItems = e.Item.FindControl("rpt_items") as Repeater;

            if (hCode == null || rptItems == null) return;
            var ds = _configService.GetList("name <> '不需要' and ParentId = (select configid from t_smd_Config where code='" + hCode.Value + "') order by seq");
            rptItems.DataSource = FindInStocks(ds.Tables[0]);
            rptItems.DataBind();
        }

        public List<t_smd_InStock> FindInStocks(DataTable dt)
        {
            var codes = (from DataRow row in dt.Rows select row["code"].ToString()).ToList();
            var list = (t_smd_InStock._Code.In(codes) & t_smd_InStock._Area == Area).List<t_smd_InStock>(Storage.Context3).ToList();
            foreach (DataRow row in dt.Rows)
            {
                if (list.All(t => t.Code != row["code"].ToString()))
                {
                    var inStock = new t_smd_InStock
                    {
                        Area = Area,
                        GroupName = _configService.GetModel(Utils.StrToInt(row["ParentId"].ToString(), 0)).Name,
                        Code = row["code"].ToString(),
                        Name = row["name"].ToString(),
                        InitQuantity = 0,
                        SendQuantity = 0,
                        Price = 0
                    };
                    list.Add(inStock);
                }
            }
            return list;
        }
    }
}